"""
学生信息管理系统 v2.0
匹配16课时教学进度，含阶段标记
"""

# ========== 第一阶段：基础结构（第1周） ==========
import json
import re


class Student:
    def __init__(self, student_id, name, age):
        """第三周添加完整验证"""
        self.student_id = student_id  # 第二周暂不验证
        self.name = name
        self.age = age


class StudentManager:
    def __init__(self):
        self.students = []

    def add_student(self, student):
        """基础添加功能"""
        self.students.append(student)


# ========== 第二阶段：持久化与验证（第2周） ==========
class EnhancedStudent(Student):
    def __init__(self, student_id, name, age, gender='U'):
        # 第四周添加正则验证
        if not re.match(r'^2023\d{4}$', student_id):
            raise ValueError("学号格式错误（示例：20230001）")

        if not re.match(r'^[A-Za-z\u4e00-\u9fa5]{2,6}$', name):
            raise ValueError("姓名必须为2-6位中文或英文")

        super().__init__(student_id, name.title(), max(15, min(int(age), 30)))
        self.gender = gender if gender in ['M', 'F'] else 'U'


class FileStudentManager(StudentManager):
    def __init__(self, filename="students.json"):
        super().__init__()
        self.filename = filename
        self._load_data()

    def _load_data(self):
        try:
            with open(self.filename, 'r', encoding='utf-8') as f:
                data = json.load(f)
                self.students = [EnhancedStudent(**item) for item in data]
        except (FileNotFoundError, json.JSONDecodeError):
            self.students = []

    def _save_data(self):
        with open(self.filename, 'w', encoding='utf-8') as f:
            data = [s.__dict__ for s in self.students]
            json.dump(data, f, ensure_ascii=False, indent=2)

    # ========== 第三阶段：完整功能（第3周） ==========
    def search(self, keyword):
        """支持学号/姓名搜索"""
        return [s for s in self.students
                if keyword.lower() in s.name.lower()
                or keyword == s.student_id]

    def delete(self, student_id):
        """根据学号删除"""
        original_count = len(self.students)
        self.students = [s for s in self.students if s.student_id != student_id]
        if len(self.students) != original_count:
            self._save_data()
            return True
        return False


# ========== 第四阶段：界面与优化（第4周） ==========
def display_menu():
    print("\n" + "=" * 30)
    print("学生信息管理系统")
    print("1.添加学生 2.查询学生 3.删除学生 4.列表显示 5.退出")
    return input("请选择操作：")


def main():
    manager = FileStudentManager()

    while True:
        choice = display_menu()

        try:
            if choice == '1':
                student = EnhancedStudent(
                    student_id=input("学号："),
                    name=input("姓名："),
                    age=input("年龄："),
                    gender=input("性别(M/F)：").upper()
                )
                manager.add_student(student)
                manager._save_data()
                print("添加成功！")

            elif choice == '2':
                keyword = input("输入学号或姓名：")
                results = manager.search(keyword)
                print(f"找到{len(results)}条记录：")
                for s in results:
                    print(f"{s.student_id} | {s.name} | {s.gender} | {s.age}岁")

            elif choice == '3':
                if manager.delete(input("输入要删除的学号：")):
                    print("删除成功")
                else:
                    print("学号不存在")

            elif choice == '4':
                print("\n全体学生列表：")
                for s in manager.students:
                    print(f"{s.student_id} | {s.name} | {s.gender} | {s.age}岁")

            elif choice == '5':
                print("系统已退出")
                break

            else:
                print("无效输入，请重新选择")

        except Exception as e:
            print(f"操作失败：{str(e)}")


if __name__ == "__main__":
    main()